<template>
  <div class="add-hospital-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>新增医院</span>
        </div>
      </template>

      <el-form
        ref="hospitalFormRef"
        :model="hospitalForm"
        :rules="hospitalRules"
        label-width="100px"
        class="hospital-form"
      >
        <!-- 医院名称 -->
        <el-form-item label="医院名称" prop="name">
          <el-input
            v-model="hospitalForm.name"
            placeholder="请输入医院名称"
            clearable
          />
        </el-form-item>

        <!-- 医院等级 -->
        <el-form-item label="医院等级" prop="level">
          <el-select
            v-model="hospitalForm.level"
            placeholder="请选择医院等级"
            clearable
          >
            <el-option label="三级甲等" value="三级甲等" />
            <el-option label="三级乙等" value="三级乙等" />
            <el-option label="二级甲等" value="二级甲等" />
            <el-option label="二级乙等" value="二级乙等" />
            <el-option label="一级甲等" value="一级甲等" />
            <el-option label="一级乙等" value="一级乙等" />
          </el-select>
        </el-form-item>

        <!-- 医院图片 -->
        <el-form-item label="医院图片">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :show-file-list="true"
            list-type="picture-card"
            accept="image/*"
          >
            <div v-if="fileList.length < 1">
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              <div class="el-upload__text">上传图片</div>
            </div>
          </el-upload>
          <div class="image-tip">建议尺寸200*90像素，大小不超过1MB</div>
        </el-form-item>

        <!-- 是否推荐 -->
        <el-form-item label="是否推荐" prop="isRecommended">
          <el-radio-group v-model="hospitalForm.isRecommended">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 医生人数 -->
        <el-form-item label="医生人数" prop="doctorCount">
          <el-input
            v-model="hospitalForm.doctorCount"
            placeholder="请输入医生人数"
            type="number"
            min="0"
            clearable
          />
        </el-form-item>

        <!-- 科室数量 -->
        <el-form-item label="科室数量" prop="departmentCount">
          <el-input
            v-model="hospitalForm.departmentCount"
            placeholder="请输入科室数量"
            type="number"
            min="0"
            clearable
          />
        </el-form-item>

        <!-- 医院科室 -->
        <el-form-item label="医院科室" prop="departments">
          <div class="departments-container">
            <div class="departments-left">
              <el-checkbox-group v-model="hospitalForm.departments">
                <el-checkbox label="内科" />
                <el-checkbox label="心内科" />
                <el-checkbox label="消化内科" />
                <el-checkbox label="内分泌科" />
                <el-checkbox label="外科" />
                <el-checkbox label="神经外科" />
                <el-checkbox label="胸外科" />
                <el-checkbox label="泌尿外科" />
                <el-checkbox label="妇产科" />
                <el-checkbox label="儿科" />
                <el-checkbox label="眼科" />
                <el-checkbox label="口腔科" />
                <el-checkbox label="皮肤科" />
                <el-checkbox label="中医科" />
              </el-checkbox-group>
            </div>
            <div class="departments-right">
              <el-tag
                v-for="dept in hospitalForm.departments"
                :key="dept"
                closable
                @close="removeDepartment(dept)"
              >
                {{ dept }}
              </el-tag>
            </div>
          </div>
        </el-form-item>

        <!-- 所在地区 -->
        <el-form-item label="所在地区" prop="region">
          <div class="region-selector">
            <el-select
              v-model="province"
              placeholder="请选择省份"
              class="province-select"
              @change="handleProvinceChange"
            >
              <el-option
                v-for="item in provinces"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <el-select
              v-model="city"
              placeholder="请选择城市"
              class="city-select"
              :disabled="!province"
              @change="handleCityChange"
            >
              <el-option
                v-for="item in cities"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <el-select
              v-model="district"
              placeholder="请选择区县"
              class="district-select"
              :disabled="!city"
              @change="updateRegion"
            >
              <el-option
                v-for="item in districts"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </div>
        </el-form-item>

        <!-- 详细地址 -->
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="hospitalForm.address"
            placeholder="请输入详细地址"
            clearable
          />
        </el-form-item>

        <!-- 医院电话 -->
        <el-form-item label="医院电话" prop="phone">
          <el-input
            v-model="hospitalForm.phone"
            placeholder="请输入医院电话"
            clearable
          />
        </el-form-item>

        <!-- 医院介绍 -->
        <el-form-item label="医院介绍" prop="introduction">
          <div class="editor-container">
            <!-- 富文本编辑器 -->
            <div class="toolbar">
              <button type="button" @click="format('bold')"><b>B</b></button>
              <button type="button" @click="format('italic')"><i>I</i></button>
              <button type="button" @click="format('underline')"><u>U</u></button>
              <button type="button" @click="format('strikeThrough')"><s>S</s></button>
              <button type="button" @click="format('justifyLeft')">左对齐</button>
              <button type="button" @click="format('justifyCenter')">居中</button>
              <button type="button" @click="format('justifyRight')">右对齐</button>
              <button type="button" @click="format('insertOrderedList')">序号</button>
              <button type="button" @click="format('insertUnorderedList')">列表</button>
              <button type="button" @click="format('createLink')">链接</button>
              <button type="button" @click="format('unlink')">取消链接</button>
            </div>
            <div
              class="editor"
              contenteditable
              v-html="hospitalForm.introduction"
              @input="handleEditorInput"
            ></div>
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <div class="button-group">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

/**
 * 新增医院组件
 * 用于管理员添加新的合作医院信息
 */

// 表单引用
const hospitalFormRef = ref<FormInstance>();

// 文件列表
const fileList = ref<FileItem[]>([]);

// 编辑器内容变化处理
const handleEditorInput = (e: Event) => {
  const target = e.target as HTMLElement;
  hospitalForm.introduction = target.innerHTML;
};

// 格式化编辑器内容
const format = (command: string, value?: string) => {
  document.execCommand(command, false, value);
};
// 医院表单数据
const hospitalForm = reactive<HospitalForm>({
  name: '',
  level: '',
  isRecommended: false,
  doctorCount: 0,
  departmentCount: 0,
  departments: [],
  region: '',
  address: '',
  phone: '',
  introduction: '',
  imageUrl: '',
});

// 地区数据
const province = ref('');
const city = ref('');
const district = ref('');

// 省份数据（简化版）
const provinces = [
  { code: '110000', name: '北京市' },
  { code: '120000', name: '天津市' },
  { code: '130000', name: '河北省' },
  { code: '140000', name: '山西省' },
  { code: '150000', name: '内蒙古自治区' },
  { code: '210000', name: '辽宁省' },
  // 更多省份可根据需要添加
];

// 城市数据（简化版）
const cities = ref<RegionItem[]>([]);
const districts = ref<RegionItem[]>([]);

// 表单规则
const hospitalRules = reactive<FormRules<HospitalForm>>({
  name: [
    { required: true, message: '请输入医院名称', trigger: 'blur' },
    { min: 2, max: 50, message: '医院名称长度在 2 到 50 个字符之间', trigger: 'blur' },
  ],
  level: [
    { required: true, message: '请选择医院等级', trigger: 'change' },
  ],
  doctorCount: [
    { required: true, message: '请输入医生人数', trigger: 'blur' },
    { type: 'number', min: 0, message: '医生人数不能为负数', trigger: 'blur' },
  ],
  departmentCount: [
    { required: true, message: '请输入科室数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '科室数量不能为负数', trigger: 'blur' },
  ],
  departments: [
    { required: true, message: '请选择医院科室', trigger: 'change' },
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' },
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 200, message: '详细地址长度在 5 到 200 个字符之间', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入医院电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入有效的电话号码', trigger: 'blur' },
  ],
  introduction: [
    { required: true, message: '请输入医院介绍', trigger: 'blur' },
    { min: 10, max: 1000, message: '医院介绍长度在 10 到 1000 个字符之间', trigger: 'blur' },
  ],
});

/**
 * 提交表单
 */
const submitForm = async () => {
  try {
    // 表单验证
    await hospitalFormRef?.validate();

    // 如果有文件，处理文件上传
    if (fileList.value.length > 0) {
      // 模拟文件上传
      const file = fileList.value[0].raw;
      if (file) {
        // 实际项目中这里应该调用上传接口
        // 为了演示，我们使用一个模拟的URL
        hospitalForm.imageUrl = `https://example.com/uploads/${Date.now()}-${file.name}`;
      }
    }

    // 模拟提交表单数据
    // 实际项目中这里应该调用后端API
    console.log('提交的医院数据:', hospitalForm);

    ElMessageBox.success('医院添加成功！');

    // 重置表单
    resetForm();
  } catch (error: any) {
    console.error('表单验证失败:', error);
    ElMessage.error('表单验证失败，请检查输入内容');
  }
};

/**
 * 重置表单
 */
const resetForm = () => {
  hospitalFormRef?.resetFields();
  fileList.value = [];
  province.value = '';
  city.value = '';
  district.value = '';
};

/**
 * 移除选中的科室
 * @param dept - 要移除的科室名称
 */
const removeDepartment = (dept: string) => {
  const index = hospitalForm.departments.indexOf(dept);
  if (index !== -1) {
    hospitalForm.departments.splice(index, 1);
  }
};

/**
 * 处理省份选择变化
 * @param value - 选中的省份代码
 */
const handleProvinceChange = (value: string) => {
  // 模拟根据省份获取城市数据
  // 实际项目中这里应该调用后端API
  if (value === '110000') {
    cities.value = [
      { code: '110100', name: '北京市' },
    ];
  } else if (value === '120000') {
    cities.value = [
      { code: '120100', name: '天津市' },
    ];
  } else if (value === '130000') {
    cities.value = [
      { code: '130100', name: '石家庄市' },
      { code: '130200', name: '唐山市' },
      { code: '130300', name: '秦皇岛市' },
      // 更多城市
    ];
  }

  // 重置城市和区县
  city.value = '';
  district.value = '';
  hospitalForm.region = '';
};

/**
 * 处理城市选择变化
 * @param value - 选中的城市代码
 */
const handleCityChange = (value: string) => {
  // 模拟根据城市获取区县数据
  // 实际项目中这里应该调用后端API
  if (value === '110100') {
    districts.value = [
      { code: '110101', name: '东城区' },
      { code: '110102', name: '西城区' },
      { code: '110105', name: '朝阳区' },
      { code: '110106', name: '丰台区' },
      // 更多区县
    ];
  }

  // 重置区县
  district.value = '';
  hospitalForm.region = '';
};

/**
 * 更新地区信息
 */
const updateRegion = () => {
  if (province.value && city.value && district.value) {
    // 实际项目中这里应该根据代码获取对应的名称
    // 为了演示，我们直接使用代码
    hospitalForm.region = `${province.value}-${city.value}-${district.value}`;
  }
};

/**
 * 文件项接口
 */
interface FileItem {
  name: string;
  url?: string;
  raw?: File;
}

/**
 * 医院表单接口
 */
interface HospitalForm {
  name: string;
  level: string;
  isRecommended: boolean;
  doctorCount: number;
  departmentCount: number;
  departments: string[];
  region: string;
  address: string;
  phone: string;
  introduction: string;
  imageUrl: string;
}

/**
 * 地区项接口
 */
interface RegionItem {
  code: string;
  name: string;
}
</script>

<style lang="scss" scoped>
.add-hospital-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-card {
  margin-bottom: 20px;
}

.hospital-form {
  margin-top: 20px;
}

.image-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.departments-container {
  display: flex;
  gap: 20px;
}

.departments-left {
  flex: 1;
  max-height: 200px;
  overflow-y: auto;
  padding-right: 10px;
}

.departments-right {
  flex: 1;
  min-height: 200px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-content: flex-start;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.toolbar {
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  padding: 5px 10px;
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.toolbar button {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 2px 8px;
  cursor: pointer;
  font-size: 12px;
}

.toolbar button:hover {
  background-color: #f0f0f0;
}

.editor {
  min-height: 200px;
  padding: 10px;
  outline: none;
}

.editor:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
.region-selector {
  display: flex;
  gap: 10px;
}

.province-select,
.city-select,
.district-select {
  flex: 1;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
</style>